package com.postliu.kwai

import android.util.Log
import com.kwai.auth.ILoginListener
import com.kwai.auth.KwaiAuthAPI
import com.kwai.auth.common.InternalResponse
import com.kwai.auth.common.KwaiConstants
import com.kwai.auth.login.kwailogin.KwaiAuthRequest
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.FlutterPlugin.FlutterPluginBinding
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result

class KwaiPlugin : FlutterPlugin, MethodCallHandler, ActivityAware {

    companion object {
        private const val TAG = "KwaiPlugin"
        private const val Init = "init"
        private const val AuthorLogin = "authorLogin"
        private const val Callback = "callback"
    }

    private lateinit var channel: MethodChannel

    private lateinit var binding: ActivityPluginBinding

    override fun onAttachedToActivity(binding: ActivityPluginBinding) {
        this.binding = binding
    }

    override fun onDetachedFromActivityForConfigChanges() {

    }

    override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
        this.binding = binding
    }

    override fun onDetachedFromActivity() {

    }

    override fun onAttachedToEngine(flutterPluginBinding: FlutterPluginBinding) {
        channel = MethodChannel(flutterPluginBinding.binaryMessenger, "kwai")
        channel.setMethodCallHandler(this)
    }

    override fun onMethodCall(call: MethodCall, result: Result) {
        Log.i(TAG, "onMethodCall: ${call.method}")
        when (call.method) {
            Init -> {
                handleInit(result)
            }

            AuthorLogin -> {
                handleAuthorLogin(result)
            }
        }
    }

    /**
     * 授权登录
     */
    private fun handleAuthorLogin(result: Result) {
        val platformArray =
            arrayOf(KwaiConstants.Platform.KWAI_APP, KwaiConstants.Platform.NEBULA_APP)
        val request = KwaiAuthRequest.Builder().setState("state_str")
            .setAuthMode(KwaiConstants.AuthMode.AUTHORIZE).setLoginType(KwaiConstants.LoginType.APP)
            .setPlatformArray(platformArray).build()
        val state = KwaiAuthAPI.getInstance()
            .sendRequest(binding.activity, request, object : ILoginListener {
                override fun onSuccess(response: InternalResponse) {
                    Log.i(
                        TAG,
                        "onSuccess: ${response.errorCode},${response.errorMsg},${response.code}"
                    )
                    val data = mapOf(
                        "code" to response.errorCode,
                        "msg" to response.errorMsg,
                        "data" to response.code,
                    )
                    channel.invokeMethod(Callback, data)
                }

                override fun onFailed(state: String?, errCode: Int, errMsg: String?) {
                    Log.e(TAG, "onFailed: $state,$errCode,$errMsg")
                    val data = mapOf(
                        "code" to errCode,
                        "msg" to errMsg,
                        "data" to state,
                    )
                    channel.invokeMethod(Callback, data)
                }

                override fun onCancel() {
                    Log.i(TAG, "onCancel: 取消了授权")
                    val data = mapOf(
                        "code" to -1,
                        "msg" to "用户取消授权",
                        "data" to null,
                    )
                    channel.invokeMethod(Callback, data)
                }
            })
        result.success(state.toString())
    }

    /**
     * 初始化快手SDK
     */
    private fun handleInit(result: Result) {
        KwaiAuthAPI.init(binding.activity.application)
        val appId = KwaiAuthAPI.getInstance().appId
        if (appId.isNotEmpty()) {
            result.success("success!")
        } else {
            result.success("failed! appId is empty,check build.gradle,see https://open.kuaishou.com/platform/openApi?menu=11")
        }
    }

    override fun onDetachedFromEngine(binding: FlutterPluginBinding) {
        channel.setMethodCallHandler(null)
    }
}
